package com.pangus.ims.mes.controller;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.pangus.LogConstants;
import com.pangus.PangusConstants;
import com.pangus.common.dto.EditDataResult;
import com.pangus.common.dto.JqGridRequest;
import com.pangus.common.dto.JqGridResponse;
import com.pangus.common.dto.JsonRequest;
import com.pangus.common.sys.dto.domain.LogDto;
import com.pangus.common.sys.utils.CommonUtils;
import com.pangus.common.sys.utils.ParamUtils;
import com.pangus.common.sys.utils.SysContextHolder;
import com.pangus.fa.controller.BaseController;
import com.pangus.ims.file.FileUtils;
import com.pangus.ims.mes.dto.domain.MesProdExchConfigDtDto;
import com.pangus.ims.mes.dto.domain.MesProdExchConfigDto;
import com.pangus.ims.mes.form.MesProdExchConfigDtForm;
import com.pangus.ims.mes.form.MesProdExchConfigForm;
import com.pangus.ims.mes.form.MesProdPlanHdForm;
import com.pangus.ims.mes.service.MesMoExchConfigService;
import com.pangus.ims.mes.service.MesProdExchConfigService;
import com.pangus.ims.mes.service.MesUserResourceByCodeService;

import cn.hutool.core.net.URLDecoder;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/mesmoexchconfig")
public class MesMoExchConfigController extends BaseController {
	 	@Autowired
	    private MesProdExchConfigService mesProdExchConfigService;
	 	
	 	@Autowired
	 	private MesMoExchConfigService mesMoExchConfigService;
	 	
	 	 @Autowired
	     private MesUserResourceByCodeService mesUserResourceByCodeService;
	    
	    @ApiOperation(value = "跳转", httpMethod = "GET", hidden = true)
	    @RequestMapping(value = { "/{path}" })
	    public ModelAndView path(@PathVariable String path, @RequestParam(value="id", required=false) String id, @RequestParam(value="type", required=false) String type) {
	        ModelAndView modelAndView = new ModelAndView("mes/mesmoexchconfig/" + path);
	        String userCode =  SysContextHolder.get().getUserDto().getUserCode();
	        Boolean hasHour = mesUserResourceByCodeService.HasUserResourceByCode("X643006744070524928", userCode);
	        modelAndView.addObject("isHour", hasHour);
	        modelAndView.addObject("type", type);
	        modelAndView.addObject("id", id);
	        logger.info("/mesmoexchconfig/" + path);
	        return modelAndView;
	    }
	    

	    /**
	     *	 删除图片
	     * 	@param file
	     *  @return string
	     *  @author ruiming2
	     */
	    @ApiOperation(value = "删除图片", httpMethod = "POST")
	    @RequestMapping(value = "/deletePicture", produces = "application/json;charset=UTF-8")
	    public EditDataResult<MesProdExchConfigDto> deletePicture(@RequestParam("deleteFile") String bodyString, HttpServletRequest request) {
			EditDataResult<MesProdExchConfigDto> result = new EditDataResult<MesProdExchConfigDto>();
			Map<String, Object> response = new HashMap<>();
	    	List<String> filePaths = new ArrayList<>();
	    	String[] params = bodyString.split(";");
	    	//进行解码
		    String imageName = URLDecoder.decode(params[0], StandardCharsets.UTF_8);
	    	String mtrlCode = params[1];
//	    	文件保存路径 ResponseEntity + mtrString,mtrlCode
	    	File fileOne = new File(FileUtils.getSavePath("/fileUpload/logo/mo/" + mtrlCode, request));
	    	if (!fileOne.exists()) {
	    		fileOne.mkdirs();
	    	}
	    	String filePathOne = fileOne.getAbsolutePath().replace(File.separator,"/");
	    	Path filePath = Paths.get(filePathOne, imageName);
	    	boolean fileExists = Files.exists(filePath);
	    	
	    	if (fileExists) {
	    		try {
	    			Files.delete(filePath);
	    			logger.info("图片删除成功！！！");
	    		} catch (Exception e) {
	    			logger.info("图片删除失败。。。。。" + e.getMessage());
				}
	    	} else {
	    		logger.info("文件不存在");
	    	}
	    	
//			获取http、ip、端口号、项目名
			String protocol = request.getScheme();
			String serverIp = request.getServerName();
			int serverPort = request.getServerPort();
			String worString = request.getContextPath();//"/ims-mes/"
			String urlPrefix = protocol + "://" + serverIp + ":" + serverPort + worString + '/';
	    	String filePathT = filePath.toString();
	    	String filePathTwo = filePathT.replace(File.separator,"/");
//			为了确保服务器的敏感信息展示在前端出现安全性问题，将logo前面的路径信息截取掉
			int logoIndex = filePathTwo.indexOf("fileUpload");
			if (logoIndex != -1) {
				String safeFilePath = filePathTwo.substring(logoIndex);
				String newFilePath = urlPrefix + safeFilePath;
//				添加路径到列表
				filePaths.add(newFilePath);
			}		

	    	response.put("message", "图片删除成功！");
	    	response.put("data", filePaths);
	    	response.put("code", PangusConstants.RESTULT_OK);
//	    	return new EditDataResult<>(response, HttpStatus.OK);
	    	result.setExtend(response);
	    	return result;
	    }

	    
	    /**
	              * 上传图片
	     * @param file
	     * @return string
	     * @author ruiming2
	     */
	    @ApiOperation(value = "上传图片", httpMethod = "POST")
	    @RequestMapping(value = "/savePicture", produces = "application/json;charset=UTF-8")
	    public EditDataResult<MesProdExchConfigDto> savePicture(@RequestParam("uploadFile") MultipartFile[] files, @RequestParam("mtrlCode") String mtrString, HttpServletRequest request) {
			EditDataResult<MesProdExchConfigDto> result = new EditDataResult<MesProdExchConfigDto>();
			Map<String, Object> response = new HashMap<>();
	    	List<String> filePaths = new ArrayList<>();
	    	if (files != null && files.length > 0) {
	    		try {
//	    			文件保存路径 ResponseEntity
	    			File fileOne = new File(FileUtils.getSavePath("/fileUpload/logo/mo/" + mtrString, request));
	    			if (!fileOne.exists()) {
	    				fileOne.mkdirs();
	    			}
	    			
//	    			获取http、ip、端口号、项目名
	    			String protocol = request.getScheme();
	    			String serverIp = request.getServerName();
	    			int serverPort = request.getServerPort();
	    			String worString = request.getContextPath();//"/ims-mes/"
	    			String urlPrefix = protocol + "://" + serverIp + ":" + serverPort + worString + '/';
	    			
//	    			增强for
	    			for (MultipartFile file : files) {
	    				if (!file.isEmpty()) {
	    	    			String fileName = file.getOriginalFilename();
	    	    			String filePath = fileOne.getAbsolutePath() + File.separator + fileName;
//	    	    			保存文件到本地
	    	    			file.transferTo(new  File(filePath));
	    	    			
	    	    			String filePathOne = filePath.replace(File.separator,"/");
//	    	    			为了确保服务器的敏感信息展示在前端出现安全性问题，将logo前面的路径信息截取掉
	    	    			int logoIndex = filePathOne.indexOf("fileUpload");
	    	    			if (logoIndex != -1) {
	    	    				String safeFilePath = filePathOne.substring(logoIndex);
	    	    				String newFilePath = urlPrefix + safeFilePath;
//	        	    			添加路径到列表
	        	    			filePaths.add(newFilePath);
	    	    			}
	    				}
	    			}
	    			response.put("message", "图片上传成功！");
	    			response.put("data", filePaths);
	    			response.put("code", PangusConstants.RESTULT_OK);
//	    			return new EditDataResult<>(response, HttpStatus.OK);
	    			result.setExtend(response);
	    			return result;
	    		} catch (IOException e) {
	    			response.put("message", "图片上传失败。。。");
	    			result.setExtend(response);
	    			return result;
	    		}
	    	} else {
	    		response.put("message", "没有选择文件上传或者上传的数据有问题。。。。");
	    		response.put("code", PangusConstants.RESTULT_FAIL);
				result.setExtend(response);
				return result;
	    	}
	    }
	    
	    
	    @ApiOperation(value = "查询", httpMethod = "POST")
	    @ApiImplicitParam(value = "需要查询的条件", required = false, dataType = "JqGridRequest<MesProdExchConfigForm>")
	    @RequestMapping(value = { "/query" }, produces = MediaType.APPLICATION_JSON_VALUE)
	    public JqGridResponse<MesProdExchConfigForm> query(@RequestBody JqGridRequest<MesProdExchConfigForm> gridRequest,HttpServletRequest request) {
	        logger.info("/mesmoexchconfig/query:" + gridRequest);
	        ParamUtils paramUtils = new ParamUtils(request);
	        JqGridResponse<MesProdExchConfigForm> gridResponse =  mesMoExchConfigService.query(gridRequest,paramUtils);
	        formUtils.fillForms(gridResponse.getData());
	        for(MesProdExchConfigForm form : gridResponse.getData()){
				form.setOrgName(messageSource.getMessage(form.getOrgName(), request.getLocale()));
			}
	        return gridResponse;
	    }
	    
	    @ApiOperation(value = "查询单个对象", httpMethod = "POST")
	    @RequestMapping(value = "/getById", produces = MediaType.APPLICATION_JSON_VALUE)
	    public EditDataResult<MesProdExchConfigForm> getById(@RequestBody MesProdExchConfigDto mesProdExchConfigDto, HttpServletRequest request) {
	    	ParamUtils paramUtils = new ParamUtils(request, new LogDto(request));
	    	EditDataResult<MesProdExchConfigForm> result = mesProdExchConfigService.getById(mesProdExchConfigDto, paramUtils);
	    	formUtils.fillForm(result.getData());
			result.getData().setOrgName(messageSource.getMessage(result.getData().getOrgName(), request.getLocale()));
	        return result;
	    }
	    
	    @ApiOperation(value = "新增", httpMethod = "POST")
	    @ApiImplicitParam(name = "mesProdExchConfigDto", value = "需要新增的对象", required = true, dataType = "MesProdExchConfigDto")
	    @RequestMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
	    public EditDataResult<MesProdExchConfigDto> add(@RequestBody JsonRequest<MesProdExchConfigForm> dtoRequest, HttpServletRequest request) {
	    	ParamUtils paramUtils = new ParamUtils(request,new LogDto(request,LogConstants.LOG_TYPE_A));
	    	EditDataResult<MesProdExchConfigDto> result = mesProdExchConfigService.add(dtoRequest, paramUtils);
	    	insertByRequest(request,paramUtils.getLogDto(), dtoRequest, dtoRequest.getForm().getMesProdExchConfigId());
	    	return result;
	    }
	    
	    @ApiOperation(value = "修改", httpMethod = "POST")
	    @ApiImplicitParam(name = "mesProdExchConfigDto", value = "需要修改的对象", required = true, dataType = "MesProdExchConfigDto")
	    @RequestMapping(value = "/edit", produces = MediaType.APPLICATION_JSON_VALUE)
	    public EditDataResult<MesProdExchConfigDto> edit(@RequestBody JsonRequest<MesProdExchConfigDto> dtoRequest, HttpServletRequest request) {
	    	ParamUtils paramUtils = new ParamUtils(request,new LogDto(request,LogConstants.LOG_TYPE_M));
	    	EditDataResult<MesProdExchConfigDto> result = mesProdExchConfigService.edit(dtoRequest,paramUtils);
	    	insertByRequest(request,paramUtils.getLogDto(), dtoRequest, dtoRequest.getForm().getMesProdExchConfigId());
	    	return result;
	    }
	    
	    @ApiOperation(value = "删除", httpMethod = "POST")
	    @ApiImplicitParam(name = "mesProdExchConfigDtoList", value = "需要删除的对象", required = true, dataType = "List<MesProdExchConfigDto>")
	    @RequestMapping(value = "/delete", produces = MediaType.APPLICATION_JSON_VALUE)
	    public EditDataResult<MesProdExchConfigDto> delete(@RequestBody JsonRequest<List<MesProdExchConfigDto>> jsonRequest, HttpServletRequest request) {
	    	ParamUtils paramUtils = new ParamUtils(request,new LogDto(request,LogConstants.LOG_TYPE_D));
	    	EditDataResult<MesProdExchConfigDto> result = mesProdExchConfigService.delete(jsonRequest.getForm(),paramUtils);
	    	insertByRequest(request, paramUtils.getLogDto(),jsonRequest.getForm(),CommonUtils.getListValueByKey(jsonRequest.getForm(), "mesProdExchConfigId", MesProdExchConfigDto.class));
	    	return result;
	    }
	    
	    @ApiOperation(value = "校验数据权限", httpMethod = "POST", hidden = true)
	    @RequestMapping(value = "/checkPointData", produces = MediaType.APPLICATION_JSON_VALUE)
	    public EditDataResult<List<String>> checkPointData(@RequestBody JsonRequest<List<MesProdExchConfigDto>> jsonRequest, HttpServletRequest request) {
	    	ParamUtils paramUtils = new ParamUtils(request, new LogDto(request));
	    	String dataPointId = jsonRequest.getExtend().get(PangusConstants.DATA_POINT_ID);
	    	return mesProdExchConfigService.checkPointData(jsonRequest.getForm(), dataPointId, paramUtils);
	    }
	    
	    @ApiOperation(value = "查询所有方案信息", httpMethod = "POST")
	    @RequestMapping(value = "/getAllProdPlanHd", produces = MediaType.APPLICATION_JSON_VALUE)
	    public EditDataResult<List<MesProdPlanHdForm>> getAllProdPlanHd(@RequestBody JsonRequest<MesProdExchConfigForm> jsonRequest, HttpServletRequest request) {
	    	ParamUtils paramUtils = new ParamUtils(request, new LogDto(request));
	        return mesProdExchConfigService.getAllProdPlanHd(jsonRequest, paramUtils);
	    }
	    
	    
	    @ApiOperation(value = "查询产品方案详情保存的数据", httpMethod = "POST")
	    @RequestMapping(value = "/getExchDetail", produces = MediaType.APPLICATION_JSON_VALUE)
	    public EditDataResult<MesProdExchConfigDtForm> getExchDetail(@RequestBody JsonRequest<MesProdExchConfigDtDto> jsonRequest, HttpServletRequest request) {
	    	ParamUtils paramUtils = new ParamUtils(request, new LogDto(request));
	        return mesProdExchConfigService.getExchDetail(jsonRequest, paramUtils);
	    }
	    
	    @ApiOperation(value = "根据erp工单号算出SN止", httpMethod = "POST")
	    @RequestMapping(value = "/countEndSn", produces = MediaType.APPLICATION_JSON_VALUE)
	    public EditDataResult<String> getSnEndCount(@RequestBody JsonRequest<String> jsonRequest,HttpServletRequest request) {
	    	ParamUtils paramUtils = new ParamUtils(request, new LogDto(request));
	    	return mesProdExchConfigService.countEndSn(jsonRequest.getExtend(),paramUtils);
	    }
	    
	    
	    @RequestMapping("/exportExcel")
		public void exportExcel(@RequestParam(name="jsonRequest") String jsonRequest, HttpServletRequest request,
				HttpServletResponse response) {
			exportExcel(MesProdExchConfigForm.class,mesProdExchConfigService);
		}
		
		@ResponseBody
		@RequestMapping("/importExcel")
		public void importExcel(@RequestParam("file")MultipartFile[] files,HttpServletRequest request, HttpServletResponse response) {
			importExcel(MesProdExchConfigForm.class,mesProdExchConfigService, files);
		}

}
